package com.example.jl.bethinner.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jl.bethinner.R;
import com.example.jl.bethinner.adapter.HELCityChooserAdapter;
import com.example.jl.bethinner.adapter.HELProvinceChooserAdapter;
import com.example.jl.bethinner.domain.BFNewModel;
import com.example.jl.bethinner.domain.City;
import com.example.jl.bethinner.domain.Province;
import com.example.jl.bethinner.fragment.CityChooserDialog;
import com.example.jl.bethinner.fragment.CityChooserDialog.OnCitySelectedLisenter;
import com.example.jl.bethinner.fragment.ProvinceChooserDialog;
import com.example.jl.bethinner.fragment.ProvinceChooserDialog.OnProvinceSelectedLisenter;
import com.google.gson.reflect.TypeToken;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

import java.util.List;

public class SelectCityDemoActivity extends ActionBarActivity implements OnClickListener, OnCitySelectedLisenter, OnProvinceSelectedLisenter, OnItemClickListener {

    private TextView tv_select;
    private TextView tv_province;
    private TextView tv_city;
    private Province selected_province;
    private City selected_city;
    private PopupWindow popupWindow;
    private List<Province> provinces;
    private HELProvinceChooserAdapter provinceAdapter = null;
    private List<City> cities;
    private HELCityChooserAdapter cityAdapter = null;
    private ListView base_listview;
    private ListView data_listview;
    ProvinceChooserDialog provinceChooserDialog;
    CityChooserDialog cityChooserDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_city_demo);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setLogo(R.mipmap.ic_launcher);
// Title
        toolbar.setTitle("My Title");
// Sub Title
        toolbar.setSubtitle("Sub title");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

        tv_select = (TextView) findViewById(R.id.tv_select);
        tv_province = (TextView) findViewById(R.id.tv_province);
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_select.setOnClickListener(this);
        provinceChooserDialog = ProvinceChooserDialog.newInstance();
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(SelectCityDemoActivity.this, "HOME", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showPopUp(View v) {
        if (null == popupWindow) {
            View contentView = LayoutInflater.from(this).inflate(
                    R.layout.activity_horizontal_expansion, null);

            base_listview = (ListView) contentView.findViewById(R.id.base_listview);
            data_listview = (ListView) contentView.findViewById(R.id.data_listview);
            setProvince();
            base_listview.setOnItemClickListener(this);
            data_listview.setOnItemClickListener(this);

            popupWindow = new PopupWindow(contentView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    tv_select.setTextColor(getResources().getColor(R.color.gray_text));
                }
            });
            popupWindow.showAsDropDown(v);

        } else {
            popupWindow.showAsDropDown(v);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_select:

                Intent intent = new Intent();
                intent.setAction("abcdefg");
                startActivity(intent);

//                tv_select.setTextColor(getResources().getColor(R.color.red_jph));
//                showPopUp(v);


//                if (null==selected_province){
//                    if (null==provinceChooserDialog){
//                        //未生成城市选择dialog
//                        provinceChooserDialog= ProvinceChooserDialog.newInstance();
//                    }
//                    provinceChooserDialog.show(getSupportFragmentManager(), "province");
//                }else {
//                    cityChooserDialog.show(getSupportFragmentManager(),"city");
//                }

                break;
        }
    }

    @Override
    public void citySelected(City city) {
        selected_city = city;
        tv_city.setText(selected_city.getCity());
    }

    @Override
    public void provinceSelected(Province provinces) {
        selected_province = provinces;
        tv_province.setText(selected_province.getProvince());
        cityChooserDialog = CityChooserDialog.newInstance(selected_province.getProvinceid());
        cityChooserDialog.show(getSupportFragmentManager(), "city");
    }

    public void setProvince() {

        Ion.with(this).load("GET", "http://zxm.buildface.com/api.php/qibo/region/allprovinces")
                .as(new TypeToken<BFNewModel<List<Province>>>() {
                }).setCallback(new FutureCallback<BFNewModel<List<Province>>>() {
            @Override
            public void onCompleted(Exception e, BFNewModel<List<Province>> result) {
                if (null == e) {
                    if (result.getStatus().equals("success")) {
                        provinces = result.getLists();
                        provinceAdapter = new HELProvinceChooserAdapter(SelectCityDemoActivity.this, provinces);
                        base_listview.setAdapter(provinceAdapter);
                        setCity(provinces.get(0).getProvinceid());
                    } else
                        Toast.makeText(SelectCityDemoActivity.this, result.getStatus(), Toast.LENGTH_SHORT).show();
                } else {
                    e.printStackTrace();
                    Toast.makeText(SelectCityDemoActivity.this, "省数据请求失败", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    public void setCity(String selectProvinceid) {
        if ("-1".equals(selectProvinceid)) {
            City whole_city = new City();
            whole_city.setCity("全国");
            whole_city.setCityid("-1");
            cities.clear();
            cities.add(whole_city);
            cityAdapter = new HELCityChooserAdapter(SelectCityDemoActivity.this, cities);
            data_listview.setAdapter(cityAdapter);
        } else {
            Ion.with(this).load("http://zxm.buildface.com/api.php/qibo/region/allcities")
                    .setBodyParameter("province_id", selectProvinceid)
                    .as(new TypeToken<BFNewModel<List<City>>>() {
                    }).setCallback(new FutureCallback<BFNewModel<List<City>>>() {
                @Override
                public void onCompleted(Exception e, BFNewModel<List<City>> result) {
                    if (null == e) {
                        if (result.getStatus().equals("success")) {
                            cities = result.getLists();
                            cityAdapter = new HELCityChooserAdapter(SelectCityDemoActivity.this, cities);
                            data_listview.setAdapter(cityAdapter);
                        } else
                            Toast.makeText(SelectCityDemoActivity.this, result.getStatus(), Toast.LENGTH_SHORT).show();
                    } else {
                        e.printStackTrace();
                        Toast.makeText(SelectCityDemoActivity.this, "市数据请求失败", Toast.LENGTH_SHORT).show();
                    }

                }
            });
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.base_listview:
                setCity(provinces.get(position).getProvinceid());
                provinceAdapter.setPositionId(position);
                break;
            case R.id.data_listview:
                tv_select.setText(cities.get(position).getCity());
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_select_city_demo, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
